//
//  EFengPhotosView.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/2/29.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "EFengPhotosView.h"
#import "EFengPhotosFrame.h"
#import "EFengPhotoView.h"
#import "EFengSharePhoto.h"
#import "EFengSharePhoto.h"
#import "MJPhotoBrowser.h"
#import "MJPhoto.h"
#import "UIImageView+WebCache.h"
#import "UIImage+ImageWithColor.h"
#import "UIImage+Category.h"
#import "CXmppRequestMgr.h"
#import "ChildHoodService.h"
#import "CContactModel.h"
#import "CContactMgr.h"
#import "RMDownloadIndicator.h"
#import "EFengVideoPlayerViewController.h"
@interface EFengPhotosView ()
@property (strong, nonatomic) NSURL *videoFileURL;
@property (strong, nonatomic) AVPlayerLayer *playerLayer;
@property (weak, nonatomic) UIButton *playButton;
@property (strong, nonatomic) AVPlayerItem *playerItem;
@property (strong , nonatomic) CContactModel *curContact;
@property (nonatomic,copy) NSString * path;
@property (nonatomic,strong) UIView *clearView;
@property (strong, nonatomic) RMDownloadIndicator *mixedIndicator;

@end

@implementation EFengPhotosView


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = ClearColor;
        self.curContact = [[[CContactMgr alloc]init] loadCurContact];
    }
    return self;
}

- (void)setPhotosFrame:(EFengPhotosFrame *)photosFrame
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    if (self.playerLayer) {
        [self.playerLayer removeFromSuperlayer];
        self.player = nil;
        self.playerItem = nil;
        _videoFileURL = nil;
        [self.clearView removeFromSuperview];
    }
    
    _photosFrame = photosFrame;
    self.frame = photosFrame.frame;
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    CGFloat gap = 5.0f;
    __block CGFloat width = 0;
    if (photosFrame.Photos.count <= 2 || photosFrame.Photos.count == 4) {
        width = (photosFrame.width - 2 * gap) / 2.0f;
    } else {
        width = (photosFrame.width - 2 * gap) / 3.0f;
    }
    if (photosFrame.videos.count > 0) {
        width =  (photosFrame.width - 2 * gap) - 30 ;
    }
    __block CGFloat height = width;
    __block CGFloat x = 0.0f;
    __block CGFloat y = 0.0f;
    
    if (photosFrame.Photos.count <= 2 || photosFrame.Photos.count == 4) {
        [photosFrame.Photos enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
            x = (idx % 2) * (width + gap);
            y = (idx / 2) * (height + gap);
            EFengPhotoView *photoView = [[EFengPhotoView alloc] init];
            photoView.tag = idx;
            if (!photosFrame.videos.count)
            {
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapForBigPicture:)];
                [photoView addGestureRecognizer:tap];
            photoView.photo = obj;
            photoView.frame = CGRectMake(x, y, width, height);
            [self addSubview:photoView];
            }
            else
            {
                height = width * 0.8;
                photoView.photo = obj;
                photoView.frame = CGRectMake(x, y, width, height);
                [self addSubview:photoView];
            }
            [photoView sd_setImageWithURL:[NSURL URLWithString:[obj stringForKey:@"url_min"]] placeholderImage:[UIImage createImageWithColor:RGBCOLOR(212, 212, 212) withBounds:self.bounds] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                photoView.image = [UIImage scaleShareImageFromImage:image scaledToWidth:width];
            }];
            
        }];
        
    } else {
        [photosFrame.Photos enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
            x = (idx % 3) * (width + gap);
            y = (idx / 3) * (height + gap);
            EFengPhotoView *photoView = [[EFengPhotoView alloc] init];
            photoView.tag = idx;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapForBigPicture:)];
            [photoView addGestureRecognizer:tap];
            
            photoView.photo = obj;
            photoView.frame = CGRectMake(x, y, width, height);
            [self addSubview:photoView];
            
            [photoView sd_setImageWithURL:[NSURL URLWithString:[obj stringForKey:@"url_min"]] placeholderImage:[UIImage createImageWithColor:RGBCOLOR(212, 212, 212) withBounds:self.bounds] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                photoView.image = [UIImage scaleShareImageFromImage:image scaledToWidth:width];
            }];
            
        }];
        
    }
    if (photosFrame.videos.count > 0) {
        [self editvideoView];
    }
}
-(void)editvideoView
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(avPlayerItemDidPlayToEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    for (id view in self.subviews) {
        if ([view isKindOfClass:[EFengPhotoView class]]) {
            EFengPhotoView *photoview = (EFengPhotoView*)view;
            NSDictionary *dic = (NSDictionary*)self.photosFrame.videos.lastObject;
            NSString *fileName = dic[@"video"];
            if (fileName.length > 50) {
                NSRange range = [fileName rangeOfString:@"filename="];
                if (range.location != NSNotFound) {
                    fileName = [fileName substringFromIndex:range.location + range.length];
                }
            }
            NSString *folderPath = [[ChildHoodService defaultService] personalUploadVideoPathWithUserId:self.curContact.UserID];
            ;
            NSString *videoPath = [folderPath stringByAppendingPathComponent:fileName];
            _videoFileURL = [NSURL fileURLWithPath:videoPath isDirectory:NO];
            AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:_videoFileURL options:nil];
            self.playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
            self.player = [AVPlayer playerWithPlayerItem:_playerItem];
            self.player.volume = 0 ;
            self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
            _playerLayer.frame = photoview.bounds;
            _playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
            [self.layer addSublayer:_playerLayer];
            self.clearView = [[UIView alloc]init];
            _clearView.backgroundColor = [UIColor clearColor];
            _clearView.frame = photoview.bounds;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapforfullScreenPlay)];
            tap.numberOfTapsRequired = 1;
            tap.numberOfTouchesRequired = 1;
            [_clearView addGestureRecognizer:tap];
            [self addSubview:_clearView];
            UIButton *playButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [playButton addTarget:self action:@selector(downloadVideo:) forControlEvents:UIControlEventTouchUpInside];
            [playButton setImage:[UIImage imageNamed:@"video_icon"] forState:UIControlStateNormal];
            playButton.frame = photoview.bounds;
            self.playButton = playButton;
            [self addSubview:playButton];
        }
    }
}
- (void)tapForBigPicture:(UITapGestureRecognizer *)tap
{
    EFengPhotoView *photoView = (EFengPhotoView *)tap.view;
    MJPhotoBrowser *photoBrower = [[MJPhotoBrowser alloc] init];
    NSMutableArray *photos = [NSMutableArray array];
    
    int i = 0;
    for (NSDictionary *dict in self.photosFrame.Photos) {
        MJPhoto *photo = [[MJPhoto alloc] init];
        photo.url = [NSURL URLWithString:[dict[@"url_max"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        photo.srcImageView = self.subviews[i];
        [photos addObject:photo];
        i ++;
    }
    photoBrower.photos = photos;
    photoBrower.currentPhotoIndex = photoView.tag;
    [photoBrower show];
    
}
-(void)tapforfullScreenPlay
{
    EFengVideoPlayerViewController *player = [[EFengVideoPlayerViewController alloc]init];
    player.videoFileURL = _videoFileURL;
    [player show];
}
-(void)downloadVideo:(UIButton*)button
{
    button.hidden = YES;
    if ([self handleVideoUrl:_videoFileURL]) {
        [self.player play];
    }
    else
    {
        self.mixedIndicator = [[RMDownloadIndicator alloc]initWithFrame:CGRectMake(0,0, 50, 50) type:kRMMixedIndictor];
        _mixedIndicator.center = self.playButton.center;
        [_mixedIndicator setBackgroundColor:[UIColor clearColor]];
        [_mixedIndicator setFillColor:[UIColor whiteColor]];
        [_mixedIndicator setStrokeColor:[UIColor whiteColor]];
        _mixedIndicator.radiusPercent = 0.45;
        [self addSubview:_mixedIndicator];
        [_mixedIndicator loadIndicator];
        
        NSDictionary *dic = (NSDictionary*)self.photosFrame.videos.lastObject;
        __weak typeof (self) weakSelf = self;
        [[CXmppRequestMgr shareInstance] downLoadWithVideoUrl:dic[@"video"] ssuccessHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
            [weakSelf.mixedIndicator removeFromSuperview];
            dispatch_async(dispatch_get_main_queue(), ^{
                AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:_videoFileURL options:nil];
                weakSelf.playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
                weakSelf.player = [AVPlayer playerWithPlayerItem:_playerItem];
                weakSelf.player.volume = 0 ;
                weakSelf.playerLayer.player = weakSelf.player;
                [weakSelf.player play];
            });
            
        } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
            
        } progressHandle:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
            [weakSelf.mixedIndicator updateWithTotalBytes:totalBytesExpectedToRead downloadedBytes:totalBytesRead];
        }  filePath:self.path];
        
    }
    
}
-(BOOL)handleVideoUrl:(NSURL*)url
{
    NSString *filePath = [[url absoluteString] stringByReplacingOccurrencesOfString:@"file:" withString:@""];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        self.path = filePath;
        NSData *data = [NSData dataWithContentsOfURL:url];
        NSDictionary *dic = (NSDictionary*)self.photosFrame.videos.lastObject;
        if (data.length >= [dic[@"length"] integerValue]) {
            return YES;
        }
        else
        {
            return NO;
        }
    }
    else
    {
        [fileManager createFileAtPath:filePath contents:nil attributes:nil];
        self.path = filePath;
        return NO;
    }
    
}
-(void)avPlayerItemDidPlayToEnd:(NSNotification*)notificaiton
{
    if ((AVPlayerItem *)notificaiton.object != _playerItem) {
        return;
    }
    [_playerItem seekToTime:kCMTimeZero];
    [self.player play];
}
@end
